package com.softlab.logsystem.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.softlab.logsystem.common.ErrorMessage;
import com.softlab.logsystem.common.GlobalConst;
import com.softlab.logsystem.common.RestData;
import com.softlab.logsystem.common.exception.LogException;
import com.softlab.logsystem.core.model.LogDto;
import com.softlab.logsystem.service.ProducerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

/**
 * @author LiXiwen
 * @date 2020/1/7 14:51
 */
@Service
public class ProducerServiceImpl implements ProducerService {
    private static final Logger logger = LoggerFactory.getLogger(ProducerServiceImpl.class);

    private final ObjectMapper objectMapper;
    private final RabbitTemplate rabbitTemplate;
    private final Environment env;

    @Autowired
    public ProducerServiceImpl(ObjectMapper objectMapper, RabbitTemplate rabbitTemplate, Environment env) {
        this.objectMapper = objectMapper;
        this.rabbitTemplate = rabbitTemplate;
        this.env = env;
    }

    @Override
    public RestData sendlogDto(LogDto logDto) throws LogException {
        try {
            rabbitTemplate.setExchange(GlobalConst.EXCHANGE_NAME);
            rabbitTemplate.setRoutingKey(GlobalConst.ROUTING_KEY_NAME);
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            Message message = MessageBuilder.withBody(objectMapper.writeValueAsBytes(logDto)).setDeliveryMode(MessageDeliveryMode.PERSISTENT).build();
            message.getMessageProperties().setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, MessageProperties.CONTENT_TYPE_JSON);
            rabbitTemplate.convertAndSend(message);
        } catch (Exception e) {
            logger.warn(ErrorMessage.SEND_ERROR + e.getMessage());
            throw new LogException(ErrorMessage.SEND_ERROR + e.getLocalizedMessage());
        }
        return new RestData("Send Object Message Success");
    }
}
